package com.lovo.dao;
import java.sql.*;

public class BaseDAO {
    protected Connection con;
    protected boolean isAutoCommit;

    public BaseDAO(){
        this.getConnection();
    }

    public Connection getConnection(){
        try {
            // 1.加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2.获取连接
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/room?" +
                    "userSSL=true&useUnicode=true&" +
                    "characterEncoding=UTF8&serverTimezone=GMT","root","lovo");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }
    public void close(Connection con, Statement statement){
        if(statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(con != null && isAutoCommit){
            try {
                con.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public void close(Connection con, Statement statement, ResultSet result){
        if(result != null){
            try {
                result.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        close(con,statement);
    }

    public void setAutoCommit(boolean isAutoCommit){
        this.isAutoCommit = isAutoCommit;
        try {
            con.setAutoCommit(isAutoCommit);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public void commit(){
        try {
            con.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally{
            if(con != null){
                try {
                    con.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    public void rollback(){
        try {
            con.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            if(con != null){
                try {
                    con.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
